local Text = GLOBAL.require "widgets/text"
local TextEdit = GLOBAL.require "widgets/textedit"
local Image = GLOBAL.require "widgets/image"
local ImageButton = GLOBAL.require "widgets/imagebutton"
local UserCommands = GLOBAL.require("usercommands")
local ISFWQ = GLOBAL.TheNet:GetIsServer() or GLOBAL.TheNet:IsDedicated()
local Ass = {}
local FenLiu_tabl = GetModConfigData("RenShu")
local TeBie = GetModConfigData("tebie")
local Fen_Liu= GetModConfigData("Fen_Liu")
local Dong_Kou= GetModConfigData("Dong_Kou")



Assets = Ass

local shangzhao = {}
local zl = {"QMPDRS"}


local Wss = {}


GLOBAL.table.insert(Wss,"z_t")

PrefabFiles = Wss


TUNING.SHARD_ID_TAB= {
	{x=4,z=0, id = "1"},
	{x=7,z=0, id = "2"},
	{x=10,z=0, id = "3"},
	{x=13,z=0, id = "4"},
	{x=4,z=5, id = "5"},
	{x=7,z=5, id = "6"},
	{x=10,z=5, id = "7"},
	{x=13,z=5, id = "8"},
	{x=4,z=10, id = "9"},
	{x=7,z=10, id = "10"},
	{x=10,z=10, id = "11"},
	{x=13,z=10, id = "12"},
	{x=4,z=-5, id = "13"},
	{x=7,z=-5, id = "14"},
	{x=10,z=-5, id = "15"},
	{x=13,z=-5, id = "16"},
	{x=4,z=-10, id = "17"},
	{x=7,z=-10, id = "18"},
	{x=10,z=-10, id = "19"},
	{x=13,z=-10, id = "20"},

}

TUNING.shijie_num=0

for k,v in pairs(FenLiu_tabl) do
	if v then
		TUNING.shijie_num=TUNING.shijie_num+1
	end
end
if Dong_Kou then
for k,v in pairs(TUNING.SHARD_ID_TAB) do
	if k<=TUNING.shijie_num and v then
		if GLOBAL.TheNet:GetIsServer() then
			AddPrefabPostInit("multiplayer_portal", function(inst)

					inst:AddComponent("spawn_entrance")
					inst:DoPeriodicTask(.1, function()
						local id = GLOBAL.TheShard:GetShardId()

						inst.components.spawn_entrance.id = id
						inst.components.spawn_entrance:Init()
					end)

			end)
		end
	end
end
end
local function wangyefn(inst)
    local wy = inst._wangye:value()
    if wy then
	GLOBAL.VisitURL(wy)
    end
end

local function plfn(str)
    if not str or srt == "" then
	return false
    end

    for k,v in pairs(zl) do
	if string.find(str,v) ~= nil then
	    return true
	end
    end

    return false
end

AddPlayerPostInit(function(inst)
    inst._wangye = GLOBAL.net_string(inst.GUID, "_WangYe", "qm_wangye")
    inst:ListenForEvent("qm_wangye", wangyefn)
end)

--[[if not ISFWQ then
AddClassPostConstruct("widgets/controls", function(self)
    local CHAT = GLOBAL.require "widgets/qm_chatqueue"
    self.networkchatqueue = self.chat_queue_root:AddChild(CHAT(self.owner))
end)
end--]]

local function dantu(inst,owner)
    if inst and owner then

	local guimo = 1
	inst:SetNormalScale(.1)
	inst:SetFocusScale(.1)
	owner:StartThread(function()
		inst:Show()

		while inst and inst:IsVisible() and guimo < 9 do
			guimo = guimo + 3
			local w = guimo / 10
			inst:SetNormalScale(w)
			GLOBAL.Sleep(0.03)
		end

		inst:SetClickable(true)
		inst:SetNormalScale(.9)
		inst:SetFocusScale(.95)

		GLOBAL.Sleep(5)

		inst:Kill()
	end)
    end
end


GLOBAL.Networking_Announcement = function(message, colour, announce_type)
	if ISFWQ then
	    if message and plfn(message) then
		local A = string.sub(message,7,8)
		local B = string.sub(message,9,10)
		local C = GLOBAL.tonumber(A) or 1
		local D = GLOBAL.tonumber(B) or 0
		local E = C..""

		if not GLOBAL.TheWorld._FENLIU then
	    	    GLOBAL.TheWorld._FENLIU = {}
		end
		if not FENLIU123 then
	    	    FENLIU123 = {}
		end
		GLOBAL.TheWorld._FENLIU[E] = D
		for i=1,TUNING.shijie_num do
			if i..""==E then
				FENLIU123[i]=D
			else
				FENLIU123[i]=FENLIU123[i] or 0
			end
		end
		GLOBAL.TheWorld:PushEvent("qm_fenliu",{ shijie = E, renshu = D})
	    end
	end
    if GLOBAL.ThePlayer ~= nil and GLOBAL.ThePlayer.HUD ~= nil and GLOBAL.ThePlayer.HUD.eventannouncer.inst:IsValid() then
	if message and shangzhao[message] ~= nil then
	    local danmu = GLOBAL.ThePlayer.HUD.eventannouncer:AddChild(ImageButton(shangzhao[message][1],shangzhao[message][2],shangzhao[message][2],shangzhao[message][2]))
	    danmu:SetPosition(0,-400)
	    danmu:SetClickable(false)
	    danmu:SetNormalScale(.1)
	    danmu:SetFocusScale(.1)
	    danmu:Hide()
	    dantu(danmu,GLOBAL.ThePlayer)
	    danmu:SetOnClick(function() danmu:Hide() GLOBAL.TheNet:Say("HONGBAO_L", true, false) end)
	elseif message and plfn(message) then
	    return
	else
	    GLOBAL.ThePlayer.HUD.eventannouncer:ShowNewAnnouncement(message, colour, announce_type)
	end

    end
end



if ISFWQ then
local old_MIGRATE = GLOBAL.ACTIONS.MIGRATE.fn
GLOBAL.ACTIONS.MIGRATE.fn = function(act)
    if act.doer ~= nil and act.target ~= nil and act.target.components.worldmigrator ~= nil then
	local A = act.target.components.worldmigrator.linkedWorld
	local B = act.target._fenliu_max or 10
	if not GLOBAL.TheWorld._FENLIU or GLOBAL.TheWorld._FENLIU[A] == nil or act.doer.Network:IsServerAdmin() then
	    return old_MIGRATE(act)
	elseif GLOBAL.TheWorld._FENLIU[A] >= B then
	    if act.doer.components.talker then
		act.doer:DoTaskInTime(0.01, function(player)
		    if player.components.talker then player.components.talker:Say("目标世界人数达到上限，无法进入") end
		end)
	    end
	    return false
	else
	    return old_MIGRATE(act)
	end
    end

    return old_MIGRATE(act)

end


local function OnDespawn(inst)
	if inst.oldOnDespawn ~= nil then
		inst.oldOnDespawn(inst)
	end
	local Rs = (#GLOBAL.AllPlayers - 1) < 0 and 0 or #GLOBAL.AllPlayers - 1
	local Rd = GLOBAL.TheShard:GetShardId()
	local Rsr = "QMPDRS"..string.format("%02d%02d",Rd,Rs)
	Rsr = Rsr..string.format("%X",math.random(2462132,5032156))
	GLOBAL.TheNet:Announce(Rsr)
end


AddPlayerPostInit(function(inst)
    inst.oldOnDespawn = inst.OnDespawn
    inst.OnDespawn = OnDespawn
    inst:DoTaskInTime(0, function()
	local Rs = #GLOBAL.AllPlayers
	local Rd = GLOBAL.TheShard:GetShardId()
	local Rsr = "QMPDRS"..string.format("%02d%02d",Rd,Rs)
	Rsr = Rsr..string.format("%X",math.random(2462132,5032156))
	GLOBAL.TheNet:Announce(Rsr)
    end)
end)

local function fenliufn(inst,data)
    local A = inst.components.worldmigrator.linkedWorld or 1
    local B = inst._fenliu_max

    if inst._fenliu_zt == nil then
	inst._fenliu_zt = GLOBAL.SpawnPrefab("z_t")
	inst._fenliu_zt.entity:SetParent(inst.entity)
	local sstr = A.."世界人数\n0/"..B.."\n↓"
	inst._fenliu_zt:Stext(sstr,1,20,2,true)
    end
    
    if data and data.shijie and data.shijie == A then
	local D = data.renshu or 0
	local YanSe = (D/B) > .8 and 3 or (D/B) > .5 and 5 or 2
	local sstr = A.."世界人数\n"..D.."/"..B.."\n↓"
	inst._fenliu_zt:Stext(sstr,1,20,YanSe,true)
    end
end



local dongxue = {"cave_entrance","cave_entrance_open","cave_exit"}
for k,v in pairs(dongxue) do
AddPrefabPostInit(v, function(inst)
    inst:AddTag("_DongKou")
    inst._fenliu_max = 10
    inst:DoTaskInTime(0, function()
	if FenLiu_tabl[inst.components.worldmigrator.linkedWorld] then
	    inst._fenliu_max = FenLiu_tabl[inst.components.worldmigrator.linkedWorld]
	end
    end)

    inst:ListenForEvent("qm_fenliu", function(world, data) fenliufn(inst, data) end, GLOBAL.TheWorld)
end)
end
end
if Fen_Liu then
AddPlayerPostInit(function(inst)
	if ISFWQ and inst.components.age and inst.components.age:GetAge()<=15 then
		local old = inst.OnNewSpawn or function() return true end
		inst.OnNewSpawn = function(inst)
			inst:DoTaskInTime(0, function()
				if inst and inst:IsValid() and FENLIU123 then

					local minnum = 12
					local minshijie=1
					local new_tab={}				
					for i=1,TUNING.shijie_num do
						new_tab[i]=i
						for k,v in pairs(TeBie) do
							if i==v  then
								new_tab[i]=0
							end
						end
					end
					for i=1,TUNING.shijie_num do
						if FENLIU123[i]<minnum and i==new_tab[i] then
							minnum=FENLIU123[i]
							
						end
						--print(i.."世界人数:"..FENLIU123[i])
					end
					--print(TUNING.shijie_num)
					--print("最小人数"..minnum)
					for i=1,TUNING.shijie_num do
						if  FENLIU123[i]==minnum and i==new_tab[i] then
							minshijie=i
							break
						end
					end
					
					--print("最小世界"..minshijie)

					if minshijie~=1   then
						local shijie123=""..minshijie..""
						--print(shijie123)
						local x,y,z =inst.Transform:GetWorldPosition()
						local ents = TheSim:FindEntities(x,y,z, 40)
						for k,v in pairs(ents) do
							if v 
								and v.prefab == "cave_entrance_open"
								and v.components.worldmigrator
								and v.components.worldmigrator.linkedWorld  
								and v.components.worldmigrator.linkedWorld  == shijie123
								then
								--print(v.components.worldmigrator.linkedWorld)
								v.components.worldmigrator:Activate(inst)
								--print("成功")
								break
							end
						end
					end
				end
			end)
			return old(inst)
		end
	end
end)
end